package com.jd.basic.interceptor;

import com.jd.basic.jwt.JwtUtils;
import com.jd.basic.jwt.LoginData;
import com.jd.basic.jwt.RsaUtils;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 发送请求之前进行拦截
        String token = request.getHeader("token");
        if (token != null){ // 代表有token信息
//        Object loginData = redisTemplate.opsForValue().get(token); // 获取登陆人信息
//            if (loginData != null){ // 有登陆人信息,发请求之后重新设置过期时间和信息
//                redisTemplate.opsForValue().set(token,loginData,30, TimeUnit.MINUTES);
//                return true;
//            }
            // 有token获取公钥进行解密
            try {
                PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                JwtUtils.getInfoFromToken(token,publicKey, LoginData.class);
                return true;
                // 这里应该刷新过期时间
            } catch (ExpiredJwtException e) { // 登录过期
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println("{\"success\":false,\"message\":\"toLogin\"}");
                return false;
            }
        }
        // 没有token信息，向前端响应json数据
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println("{\"success\":false,\"message\":\"toLogin\"}");
        return false;
    }
}
